

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    /*
        判断二叉树是否是高度平衡的(每个结点都必须高度平衡)
        思路：遍历子树所有结点，只要有任意一个结点平衡因子大于1，该二叉树就不是高度平衡的
    */
    public boolean isBalanced(TreeNode root) {
        //结点是空，或者是叶结点，都是高度平衡的
        if (root == null || root.left==null && root.right==null){
            return true;
        }
        if (balanceFactor(root)>1){
            return false;
        }
        if (!isBalanced(root.left)){
            return false;
        }
        if (!isBalanced(root.right)){
            return false;
        }
        return true;
    }
    //计算某节点的高度
    public int computingHeight(TreeNode root) {
        //空节点 高度是0
        if (root == null){
            return 0;
        }
        //叶结点 高度是1
        if (root.left == null && root.right == null){
            return 1;
        }
        return Math.max(computingHeight(root.left), computingHeight(root.right))+1;
    }
    //计算某结点平衡因子(某结点的左子树与右子树的高度(深度)差的绝对值即为该结点的平衡因子)
    public int balanceFactor(TreeNode root){
        return Math.abs(computingHeight(root.left) - computingHeight(root.right));
    }
}
//leetcode submit region end(Prohibit modification and deletion)
